import cv2
import pyautogui
import numpy as np

def is_image_matched(screenshot, target_image, threshold=0.8):
    """
    使用模板匹配判断目标图像是否在截图中
    """
    if screenshot.size == 0 or target_image.size == 0:
        return False
    screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)
    target_gray = cv2.cvtColor(target_image, cv2.COLOR_BGR2GRAY)
    result = cv2.matchTemplate(screenshot_gray, target_gray, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, _, _ = cv2.minMaxLoc(result)
    return max_val >= threshold

def loop_until_appears_and_loop_action(template_path, action_when_appears, action_when_disappears, threshold=0.8):
    """
    图片没出现时一直循环，图片出现后循环执行动作，直到图片消失退出
    """
    target_image = cv2.imread(template_path)
    if target_image is None:
        print(f"无法读取目标图像: {template_path}")
        return
    target_image = cv2.cvtColor(target_image, cv2.COLOR_BGR2RGB)

    while True:
        screenshot = pyautogui.screenshot()
        screenshot = np.array(screenshot)
        screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)

        found = is_image_matched(screenshot, target_image, threshold)

        if found:
            while True:
                screenshot = pyautogui.screenshot()
                screenshot = np.array(screenshot)
                screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
                found = is_image_matched(screenshot, target_image, threshold)
                if not found:
                    action_when_disappears()
                    break
                action_when_appears()
            break
